#!/usr/bin/env python
# vim:fileencoding=UTF-8
'''
DMZ Online Stat Day
'''
import os,sys,datetime,common.db
from logging import *
from common.date_time import *

def OnlineStatDay(strCurDay): 
    log(INFO,'StatDay : '+ strCurDay)
    
    strDay = strCurDay.replace('-','')
    
    cnn = common.db.connect('billDB')
    cur = cnn.cursor()

    strSql = 'delete from statisticdb.DMZOnlineStatDay where statisticdate=%s'%(strDay)
    deletedCount = cur.execute(strSql)
    if deletedCount>0:
        log(INFO,'Data deleted successful.(deletedCount=%d)'%(deletedCount))

    strSql = '''
        insert into statisticdb.DMZOnlineStatDay
        (StatisticDate,ZoneID,MaxOnlineUserCount,MinOnlineUserCount,AvgOnlineUserCount)
        select %s,ZoneID,max(PlayerCount),min(PlayerCount),round(avg(PlayerCount))
        from dmz_bill_%s.online where RoomID=0 group by ZoneID
        union all
        select %s,0,max(PlayerCount),min(PlayerCount),round(avg(PlayerCount))
        from
        (
        select sum(PlayerCount) PlayerCount
        from `dmz_bill_%s`.`online` where RoomID=0
        group by floor(unix_timestamp(BillTime)/30)
        ) tmp
        '''%(strDay,strDay,strDay,strDay)
    cur.execute(strSql)

    strSql = '''
        insert into statisticdb.DMZOnlineStatDay(StatisticDate,ZoneID,AvgOnlineDuration)
        select %s,ifnull(ZoneID,0),round(avg(OnlineTime)) from dmz_bill_%s.logout group by ZoneID with rollup
        on duplicate key update AvgOnlineDuration=values(AvgOnlineDuration)
        '''%(strDay,strDay)
    cur.execute(strSql)

    cnn.commit()
    cur.close()
    cnn.close()

if __name__ != "__main__":
    
    if len(sys.argv) > 3:
        strBeginDay = sys.argv[2]
        strEndDay = sys.argv[3]
        if len(strBeginDay) != 10:
            log(ERROR,'Param is error!')
            sys.exit(0)
        if len(strEndDay) != 10:
            log(ERROR,'Param is error!')
            sys.exit(0)
        for strCurDay in intervalDay(strBeginDay,strEndDay):
            OnlineStatDay(strCurDay)
    elif len(sys.argv) > 2:
        strCurDay = sys.argv[2]
        if len(strCurDay) != 10:
            log(ERROR,'Param is error!')
            sys.exit(0)
        OnlineStatDay(strCurDay)
    else:
        strCurDay = GetDay(-1) ##"2010-01-14"
        OnlineStatDay(strCurDay) 

